package org.example.trigger.interceptor;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.example.domain.auth.model.entity.UserEntity;
import org.example.domain.auth.service.IAuthService;
import org.example.types.utils.JwtUtils;
import org.example.types.utils.ThreadLocalUtils;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author yinghuashen
 * @version 1.0
 * @description
 * @date 2025/3/4 22:34
 */

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private IAuthService authService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("LoginInterceptor拦截器拦截请求");
        // 获取请求头中的token
        String jwtToken = request.getHeader("Authorization");
        // 判断token是否为空
        if (jwtToken == null || jwtToken.isEmpty()) {
            // 未登录，返回401状态码
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        // 验证token是否有效
        Map<String, Object> claim = JwtUtils.checkToken(jwtToken);
        if (claim == null) {
            // 未登录，返回401状态码
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        // 从Claim中获取手机号
        Object phone = claim.get("phone");
        if (phone == null) {
            // 未登录，返回401状态码
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        // 从redis中查询用户信息
        String cachedToken = authService.checkUserOnlineState((String)phone);
        // 判断token是否一致
        if (cachedToken == null || StringUtils.isBlank(cachedToken)) {
            // 未登录，返回401状态码
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        // 获取用户信息
        UserEntity userEntity = authService.getUserBasicInfoByToken(cachedToken);
        if (userEntity == null) {
            // 未登录，返回401状态码
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        // 将用户信息存入ThreadLocal中，方便后续使用
        ThreadLocalUtils.addCurrentUser(userEntity.getUserId(),
                userEntity.getUserName(),
                userEntity.getUserPhone());
        return true;
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        log.info("清除用户信息");
        // 移除用户信息
        ThreadLocalUtils.removeUser();
    }

}
